package com.coder.rental.security;

import com.coder.rental.entity.Permission;
import com.coder.rental.entity.User;
import com.coder.rental.service.IPermissionService;
import com.coder.rental.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 自定义用户详细服务类，实现Spring Security的UserDetailsService接口
 * 用于加载用户信息及权限，以支持Spring Security的认证和授权功能
 */
@Component
public class CustomerUserDetailsService implements UserDetailsService {
    // 注入用户服务，用于查询用户信息
    @Resource
    private IUserService userService;
    // 注入权限服务，用于查询用户权限信息
    @Resource
    private IPermissionService permissionService;

    /**
     * 根据用户名加载用户信息及权限
     *
     * @param username 用户名，用于查询用户信息
     * @return UserDetails 实现类，包含用户信息和权限
     * @throws UsernameNotFoundException 如果用户不存在，则抛出此异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 到数据库中按username查询用户
        User user = userService.selectByUsername(username);
        // 如果用户不存在，抛出异常
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 查询用户权限列表
        List<Permission> permissions = permissionService.selectPermissionListByUserId(user.getId());
        user.setPermissionList(permissions);
        // 通过stream流处理，将权限对象转换为权限字符串列表
        List<String> list = permissions.stream().filter(Objects::nonNull)
                .map(Permission::getPermissionCode)
                .filter(Objects::nonNull)
                .toList();
        // 将权限字符串列表转换为数组
        String[] array = list.toArray(new String[list.size()]);
        // 将权限数组转换为Spring Security所需的GrantedAuthority列表
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(array);
        user.setAuthorities(authorityList);
        /*System.out.println(user);*/
        // 返回包含用户信息和权限的User对象
        return user;
    }
}
